<template>
  <div class="similar-aside aside-mine">
    <div class="search-header">
      <el-input v-model="searchInput" size="small" placeholder="输入搜索关键字" @keyup.13.native="onSearch">
        <i class="el-icon-close" slot="suffix" @click="clearSearch" v-if="searchInput.length"></i>
        <el-button type="primary" slot="append" icon="el-icon-search" @click="onSearch"></el-button>
      </el-input>
      <el-tooltip effect="dark" content="新建分组" placement="top">
        <el-button type="primary" class="add-btn" @click="editGroup('add')">
          <icon-svg name="iconGroup"></icon-svg>
        </el-button>
      </el-tooltip>
    </div>
    <el-collapse v-model="activeCollapse" accordion v-if="groupList.length || loading">
      <el-collapse-item v-for="(item, index) in groupList" :key="item.groupId" :name="item.groupId">
        <div slot="title" class="group-title">
          <i
            class="icon-toggle"
            :class="activeCollapse === item.groupId ? 'el-icon-caret-bottom' : 'el-icon-caret-right'"
          ></i>
          <el-tooltip effect="dark" :content="item.groupNm" placement="top-start">
            <span class="name">{{ item.groupNm }}</span>
          </el-tooltip>
          <el-popover placement="right-start" width="170" trigger="hover" popper-class="tag-group-handler">
            <ul>
              <li @click="handleAdd(item)"><i class="el-icon-circle-plus-outline"></i>添加相似人群分析</li>
              <template v-if="item.groupId">
                <li @click="editGroup('edit', item)">
                  <icon-svg name="iconFacEdit" class="el-edit"></icon-svg>
                  编辑分组
                </li>
                <li @click="deleteGroup(item)">
                  <icon-svg name="iconDelete" class="el-delete"></icon-svg>
                  删除分组
                </li>
              </template>
            </ul>
            <i class="el-icon-more group-handler" slot="reference"></i>
          </el-popover>
        </div>
        <div class="data-list">
          <template v-if="item.page.results.length">
            <ul class="list-wrap">
              <li
                class="list-item"
                :class="{ 'is-active': tag.tagId === selectData.tagId }"
                v-for="tag in item.page.results"
                :key="tag.tagId"
                @click="selectItem(tag)"
              >
                <i class="el-icon-s-marketing"></i>
                <span class="list-name elli">{{ tag.tagNm }}</span>
                <i class="el-icon-success" v-if="tag.tagReqStatus === 3"></i>
                <i class="el-icon-stopwatch" v-if="tag.tagReqStatus === 1"></i>
                <i class="el-icon-error" v-if="tag.tagReqStatus === 2 || tag.tagReqStatus === 4"></i>
              </li>
            </ul>
            <el-pagination
              style="text-align: right"
              :current-page="item.page.params.currentPageNum"
              :page-size="item.page.params.pageSize"
              background
              layout="total, prev, pager, next"
              :total="item.page.totalSize"
              :pager-count="5"
              small
              @current-change="handleCurrentChange($event, index)"
            >
            </el-pagination>
          </template>
          <div class="no-record" v-else>
            <img src="~@/assets/img/no_records.png" /><br />
            暂无内容
          </div>
        </div>
      </el-collapse-item>
    </el-collapse>
    <div class="no-record" v-else>
      <img src="~@/assets/img/no_records.png" /><br />
      暂无内容
    </div>
    <tag-group ref="tagGroup" @callback="getGroupList"></tag-group>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loading: false,
      searchInput: '',
      searchKey: '',
      activeCollapse: '',
      groupList: [],
      selectData: {}
    }
  },
  created() {
    this.getGroupList()
  },
  watch: {
    activeCollapse() {
      // this.selectItem()
      if (this.activeCollapse !== '') {
        this.getDataList()
      }
    }
  },
  methods: {
    getGroupList() {
      let url =
        this.searchKey.length > 0
          ? `der/derCustExtension/getScreenPageGroup/${this.searchKey}`
          : 'ast/astTagDerivedGroup/getAllGroup/6'
      this.loading = true
      this.$ajax({
        url: this.$ajax.setUrl(url),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          let groupList = []
          if (this.searchKey.length > 0) {
            groupList = data.data || []
          } else {
            groupList = [{ groupId: 0, groupNm: '默认分组' }, ...(data.data || [])]
          }
          groupList.forEach(item => {
            item.page = {
              results: [],
              params: {
                currentPageNum: 1,
                pageSize: 10
              },
              totalSize: 0
            }
          })
          this.groupList = groupList
          if (this.activeCollapse === '' && !this.selectData.tagId) {
            if (groupList[0]) {
              this.activeCollapse = groupList[0].groupId
            }
          } else if (this.activeCollapse !== '' && this.selectData.tagId) {
            this.getDataList()
          }
        } else {
          this.$message.error(data.data || data.msg)
        }
        this.loading = false
      })
    },
    getDataList() {
      let group = this.groupList.find(item => item.groupId === this.activeCollapse)
      if (group) {
        let params = group.page.params
        this.loading = true
        this.$ajax({
          url: this.$ajax.setUrl('der/derCustExtension/selectMyCustExtension'),
          method: 'get',
          params: this.$ajax.setParams({
            currentPageNum: params.currentPageNum,
            pageSize: params.pageSize,
            queryParams: {
              groupId: group.groupId,
              tagNm: this.searchKey
            }
          })
        }).then(({ data }) => {
          if (data && data.code === '0') {
            group.page.results = data.data.records
            group.page.totalSize = data.data.totalSize
            let maxPageNum = Math.ceil(data.data.totalSize / params.pageSize) || 1
            if (params.currentPageNum > maxPageNum) {
              params.currentPageNum = maxPageNum
              this.getDataList()
            } else {
              if (data.data.records.length > 0) {
                if (this.selectData.tagId) {
                  let target = data.data.records.find(item => item.tagId === this.selectData.tagId)
                  if (target) {
                    this.selectItem(target)
                  } else {
                    this.selectItem(data.data.records[0])
                  }
                } else {
                  this.selectItem(data.data.records[0])
                }
              }
            }
          } else {
            this.$message.error(data.data || data.msg)
          }
          this.loading = false
        })
      }
    },
    onSearch() {
      this.searchKey = this.searchInput.trim()
      this.selectData = {}
      this.activeCollapse = ''
      this.getGroupList()
    },
    clearSearch() {
      this.searchInput = ''
      if (this.searchKey !== '') {
        this.onSearch()
      }
    },
    handleCurrentChange(num, index) {
      this.groupList[index].page.params.currentPageNum = num
      this.selectItem()
      this.getDataList()
    },
    selectItem(data = {}) {
      this.selectData = data
      this.$emit('selectData', data)
    },
    handleAdd(item) {
      this.$router.push({
        name: 'similar-config',
        query: {
          groupId: item.groupId
        }
      })
    },
    saveTag(groupId) {
      if (this.activeCollapse === groupId) {
        this.getDataList()
      }
    },
    editGroup(type = 'add', item = {}) {
      this.$refs.tagGroup.showDialog({ type, groupId: item.groupId, groupNm: item.groupNm, groupType: 6 })
    },
    deleteGroup(item) {
      this.$confirm(`是否确认删除分组【${item.groupNm}】?`).then(() => {
        let messageBox = document.getElementsByClassName('el-message-box__wrapper')
        messageBox[0].focus() // 防止按空格键重复确定
        this.$ajax({
          url: this.$ajax.setUrl(`ast/astTagDerivedGroup/${item.groupId}`),
          method: 'delete',
          params: this.$ajax.setParams()
        }).then(({ data }) => {
          if (data && data.code === '0') {
            if (this.activeCollapse === item.groupId) {
              this.activeCollapse = ''
            }
            this.$message.success(data.msg)
            this.getGroupList()
          } else {
            this.$message.error(data.data || data.msg)
          }
        })
      })
    },
    deleteData() {
      this.selectData = {}
      this.getDataList()
    }
  }
}
</script>

<style lang="scss"></style>
